`timescale 1ns/100ps

module cm_fft2_N2 #(
    parameter C_DATA_WITH = 16
)(
    input  wire                     I_sys_clk,       // 工作时钟 100M
    input  wire                     I_data_start,    // 数据开始进入标志，与第一个数据对齐输入
    input  wire [C_DATA_WITH-1:0]   I_data_in_real,  // 数据输入，从start开始连续输入
    input  wire [C_DATA_WITH-1:0]   I_data_in_imag,  // 数据输入，从start开始连续输入
    output reg                      O_data_start,    // 数据开始输出标志与第一个数据对齐输出
    output reg  [C_DATA_WITH:0]     O_data_out_real, // 数据输出，从start开始连续输出
    output reg  [C_DATA_WITH:0]     O_data_out_imag  // 数据输出，从start开始连续输出
);

// ============================================================
// 内部参数
// ============================================================
/// W02=1

// ============================================================
// 变量声明
// ============================================================
reg                     S_data_start;
reg [C_DATA_WITH-1:0]   S_data_in_real_d1;
reg [C_DATA_WITH-1:0]   S_data_in_real_d2;
reg [C_DATA_WITH-1:0]   S_data_in_imag_d1;
reg [C_DATA_WITH-1:0]   S_data_in_imag_d2;

// ============================================================
// 主逻辑代码
// ============================================================

// 同步输入的 start 标志
always @(posedge I_sys_clk) begin
    S_data_start <= I_data_start;
    O_data_start <= S_data_start;
end

// 缓存输入数据
always @(posedge I_sys_clk) begin
    S_data_in_real_d1 <= I_data_in_real;
    S_data_in_real_d2 <= S_data_in_real_d1;
    S_data_in_imag_d1 <= I_data_in_imag;
    S_data_in_imag_d2 <= S_data_in_imag_d1;
end

// 输出逻辑
always @(posedge I_sys_clk) begin
    if (S_data_start) begin
        // x(n) + x(n+N/2)
        O_data_out_real <= {S_data_in_real_d1[C_DATA_WITH-1], S_data_in_real_d1} + 
                           {I_data_in_real[C_DATA_WITH-1], I_data_in_real};
        O_data_out_imag <= {S_data_in_imag_d1[C_DATA_WITH-1], S_data_in_imag_d1} + 
                           {I_data_in_imag[C_DATA_WITH-1], I_data_in_imag};
    end 
    else if (O_data_start) begin
        // [x(n) - x(n+N/2)] * C_W02
        O_data_out_real <= {S_data_in_real_d2[C_DATA_WITH-1], S_data_in_real_d2} - 
                           {S_data_in_real_d1[C_DATA_WITH-1], S_data_in_real_d1};
        O_data_out_imag <= {S_data_in_imag_d2[C_DATA_WITH-1], S_data_in_imag_d2} - 
                           {S_data_in_imag_d1[C_DATA_WITH-1], S_data_in_imag_d1};
    end 
    else begin
        // 默认清零
        O_data_out_real <= 'd0;
        O_data_out_imag <= 'd0;
    end
end

endmodule